package 链表;

/**
 * https://leetcode-cn.com/problems/design-linked-list/
 *
 * @author Mxb
 * @version 1.0
 * @date 2020/3/4 21:15
 */
public class _707_设计链表 {
    // 链表容量
    private int size;
    //头节点
    private Node first;


    public static class Node {
        int val;
        Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * Get the value of the index-th node in the linked list. If the index is invalid, return -1.
     */
    public Integer get(int index) {
        Node node = node(index);
        if (node == null) return -1;
        return node.val;
    }

    /**
     * Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
     */
    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    /**
     * Append a node of value val to the last element of the linked list.
     */
    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    /**
     * Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
     */
    public void addAtIndex(int index, int val) {

        if (index == 0) {
            first = new Node(val, first);
        } else {
            // 上一个
            Node prev = node(index - 1);
            if (prev == null) return;
            Node nex = prev.next.next;
            Node newNode = new Node(val, nex);
            prev.next = newNode;
        }
        size++;

    }

    /**
     * Delete the index-th node in the linked list, if the index is valid.
     */
    public void deleteAtIndex(int index) {
        // 不做 0 判断
        Node prev = node(index - 1);
        Node nex = prev.next.next;
        prev.next = nex;
    }

    // 返回索引处的节点
    public Node node(int index) {
        Node node = first;

        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

}
